<!DOCTYPE html>
<html lang="ch">
  <head>
    <meta charset="UTF-8" />
    <title>YOLOv8 Object Detection</title>
    <style></style>
  </head>

  <body>
    <canvas id="canvas" width="640" height="480" style="display: none"></canvas>
    <canvas id="showCanvas" width="640" height="480"></canvas>
    <video
      id="video"
      width="640"
      height="480"
      autoplay
      style="display: none"
    ></video>

    <script src="//cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.0/socket.io.js"></script>
    <script>
      // 连接WebSocket服务器
      const socket = io.connect("ws://localhost:5000");

      function render() {
        const canvas = document.getElementById("canvas");
        const context = canvas.getContext("2d");
        const video = document.getElementById("video");
        context.drawImage(video, 0, 0, 640, 480);
        const imageData = canvas.toDataURL("image/png");
        return imageData;
      }

      function init() {
        if (navigator.mediaDevices.getUserMedia) {
          navigator.mediaDevices
            .getUserMedia({ video: true })
            .then(function (stream) {
              var video = document.getElementById("video");
              video.srcObject = stream;
            })
            .catch(function (error) {
              console.log("获取摄像头数据时出错：", error);
            });
        }

        socket.on("message", function (msg) {
          const imageData = render();
          draw_image_and_boxes(render(), msg);
          socket.send(imageData);
        });
        socket.send(render());
      }

      // 对象检测
      function draw_image_and_boxes(url, boxes) {
        const img = new Image();
        img.src = url;
        img.onload = () => {
          const canvas = document.querySelector("#showCanvas");
          canvas.width = img.width;
          canvas.height = img.height;
          const ctx = canvas.getContext("2d");
          ctx.drawImage(img, 0, 0);
          ctx.strokeStyle = "#00FF00";
          ctx.lineWidth = 3;
          ctx.font = "18px serif";
          boxes.forEach(([x1, y1, x2, y2, label, trust]) => {
            ctx.strokeRect(x1, y1, x2 - x1, y2 - y1);
            ctx.fillStyle = "#00ff00";
            const width = ctx.measureText(label + trust).width;
            ctx.fillRect(x1, y1, width + 10, 25);
            ctx.fillStyle = "#000000";
            ctx.fillText(label + trust, x1, y1 + 18);
          });
        };
      }

      init();
    </script>
  </body>
</html>
